package com.grq.mis.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.grq.mis.entity.Notice;
import com.grq.mis.exception.BusinessException;
import com.grq.mis.exception.ResultEnum;
import com.grq.mis.model.sys.Me;
import com.grq.mis.service.NoticeService;
import com.grq.mis.validate.NoticeValidate;
import org.beetl.sql.core.page.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/notice")
public class NoticeController extends BaseController {

    @Autowired
    private NoticeService noticeService;


    @SaCheckPermission("notice:list")
    @GetMapping("/page")
    public String page(
            Model model,
            @RequestParam(defaultValue = "1") long page,
            @RequestParam(defaultValue = "20") int size
    ) {

        // 带入参数
        Map<String, Object> paras = new HashMap<>();

        PageResult<Notice> result = noticeService.page("notice.page", paras, page, size);
        model.addAttribute("data", result);

        return "notice/page.html";
    }

    @SaCheckPermission("notice:add")
    @GetMapping("/addForm")
    public String addForm() {
        return "notice/add.html";
    }

    @SaCheckPermission("notice:add")
    @PostMapping("/add")
    public String add(Model model, Notice notice) {

        NoticeValidate.add(notice);
        Me me = me();
        noticeService.addNotice(notice,me);

        return frameSuccess(model, ResultEnum.SUCCESS, "添加消息通知成功");
    }

    @SaCheckPermission("notice:update")
    @GetMapping("/updateForm")
    public String updateForm(@RequestParam Long id, Model model) {

        Notice notice = noticeService.single(id);
        if (notice == null) {
            throw new BusinessException(ResultEnum.NOTICE_IS_NULL);
        }

        model.addAttribute("notice", notice);

        return "notice/update.html";
    }

    @SaCheckPermission("notice:update")
    @PostMapping("/update")
    public String update(Model model, Notice notice) {

        NoticeValidate.update(notice);

        noticeService.updateNotice(notice);

        return frameSuccess(model, ResultEnum.SUCCESS, "修改消息通知成功");
    }

    @SaCheckPermission("notice:delete")
    @GetMapping("/delete")
    public String delete(@RequestParam Long id, RedirectAttributes attr) {

        noticeService.deleteNotice(id);

        return pageSuccess(attr, "/notice/page", ResultEnum.SUCCESS, "删除消息通知成功");
    }

}
